package cn.itsource.ymcc.mq;

import cn.itsource.ymcc.constant.ErrorConstantCode;
import cn.itsource.ymcc.constant.MQConstants;
import cn.itsource.ymcc.domain.CourseOrder;
import cn.itsource.ymcc.domain.CourseOrderItem;
import cn.itsource.ymcc.service.ICourseOrderItemService;
import cn.itsource.ymcc.service.ICourseOrderService;
import cn.itsource.ymcc.util.AssertUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.UnsupportedEncodingException;

@Slf4j
@Service
@RocketMQTransactionListener(txProducerGroup = MQConstants.TX_COURSER_ORDER_PRODUCE_GROUP)
public class CourserOrderMQTxLinster implements RocketMQLocalTransactionListener {

    @Autowired
    private ICourseOrderService orderService;

    @Autowired
    private ICourseOrderItemService itemService;

    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object obj) {
       try {
           log.info("开始执行保存订单信息");
           CourseOrder courseOrder = (CourseOrder) obj;
           AssertUtil.isNotNull(courseOrder, ErrorConstantCode.PARAMETER_NOT_BE_NULL);

           //判断一下，订单是否存在
           Long id = courseOrder.getId();
           String orderNo = courseOrder.getOrderNo();
           Wrapper<CourseOrder> wrapper = new EntityWrapper<>();
           wrapper.eq("order_no",orderNo);
           CourseOrder courseOrder_older = orderService.selectOne(wrapper);
           if (id != null || courseOrder_older!=null) {
               log.info("订单已经保存过了");
               return RocketMQLocalTransactionState.COMMIT; // 提示MQ 发送半消息给消费者了
           }
           // 调用订单Ser去实现订单和订单项的保存
           orderService.saveOrderAndItem(courseOrder);
       }catch (Exception e){
           e.printStackTrace();
           log.info("保存订单失败！");
           return RocketMQLocalTransactionState.ROLLBACK; //通知MQ丢弃半消息
       }
        return RocketMQLocalTransactionState.COMMIT;
    }



    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        log.info("检查保存是否保存成功！");

        byte[] payload = (byte[]) message.getPayload();

        try {
            // 从消息中获取课程订单信息
            String josnStr = new String(payload,"utf-8");
            CourseOrder courseOrder = JSON.parseObject(josnStr, CourseOrder.class);
            String orderNo = courseOrder.getOrderNo();

            // 查询课程订单是否保存成功！
            Wrapper<CourseOrder> wrapper = new EntityWrapper<>();
            wrapper.eq("order_no",orderNo);
            CourseOrder courseOrder_older = orderService.selectOne(wrapper);

            if(courseOrder_older==null){
                log.info("还没保存成功！");
                return RocketMQLocalTransactionState.UNKNOWN;
            }else{
                return RocketMQLocalTransactionState.COMMIT;
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            log.info("查询订单保存状况出现异常！"); // 通知MQ 过段时间在回调检查，如果多次检查失败，就需要人工介入
            return RocketMQLocalTransactionState.UNKNOWN;
        }

    }
}
